package com.example.netty.nio.groupChat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;
import java.util.concurrent.Callable;

public class GroupChatClient {
    private Selector selector;
    private SocketChannel socketChannel;
    public static final String HOST = "127.0.0.1";
    public static final int ADDRESS = 6667;
    private String userName;

    public GroupChatClient() throws IOException {
        socketChannel = SocketChannel.open(new InetSocketAddress(HOST,ADDRESS));
        socketChannel.configureBlocking(false);

        selector = Selector.open();

        socketChannel.register(selector, SelectionKey.OP_READ,ByteBuffer.allocate(1024));

        userName = socketChannel.getLocalAddress().toString().substring(1);
    }

    public void sendMessage(String message) throws IOException {
        String info = userName+" 说:"+message;

        socketChannel.write(ByteBuffer.wrap(info.getBytes()));
    }

    public void receiveMessage() throws IOException {
        int selectResult = selector.selectNow();
        if (selectResult > 0) {
            Iterator<SelectionKey> keyIterator = selector.selectedKeys().iterator();
            while (keyIterator.hasNext()) {
                SelectionKey key = keyIterator.next();
                if (key.isReadable()) {
                    SocketChannel socketChannel = (SocketChannel)key.channel();
//                    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                    ByteBuffer byteBuffer = (ByteBuffer)key.attachment();//在注册的时候如果没有绑定buffer的话，会报错
                    socketChannel.read(byteBuffer);

                    System.out.println(new String(byteBuffer.array()).trim());
                }
                keyIterator.remove();
            }
        }
    }

    public static void main(String[] args) throws Exception {
        //需要两个线程，循环机那挺读和写
        GroupChatClient groupChatClient = new GroupChatClient();
        //新建一个线程循环读
        new Thread(){
            public void run() {
                while (true) {
                    try {
                        groupChatClient.receiveMessage();
                        Thread.sleep(1000);
                    } catch (IOException | InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }.start();

        //用主线程监听写
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            String message = scanner.nextLine();
            groupChatClient.sendMessage(message);
        }
    }
}
